<?php

namespace Modules\H5\Http\Controllers\My;

use Modules\Common\Models\Ebooks;
use Modules\Common\Models\SearchRecords;
use Modules\Common\Models\Orders;
use Modules\Common\Models\Users;
use Modules\Common\Models\UserReadingRecords;
use Modules\Common\Util\Api;
use Modules\Common\Util\Database;
use Carbon\Carbon;

class My
{
    
    /**
     * 获取用户的基本信息和会员信息
	 * @Route(path=/api/h5/get-user-info)
     */
    public function getUserInfo()
    {
        $userId = auth('web')->user()->id; // 获取当前认证的用户ID
        // 预加载用户的会员信息
        $userWithMember = Users::with(['members'])->find($userId);
        $isMemberExpired = true;
        foreach ($userWithMember->members as $member) {
            if ($member->status == 2) {
                $isMemberExpired = false;
                break;
            }
        }
        $userWithMember->is_member = $isMemberExpired;
        return Api::success($userWithMember);
    }
    /**
     * 获取用户的订单列表
     * @Route(path=/api/h5/my-orders)
     */
    public function myOrders()
    {
        $userId = auth('web')->user()->id; // 获取当前认证的用户ID
        $eid = auth('web')->user()->eid;
        $status = request('status');
        $query = Orders::where('user_id', $userId)->with(['ebook','member','subscriptionTypes']);
        // 如果 $status 参数不为空，则添加该条件
        if (!empty($status)) {
            $query->where('status', $status);
        }
        $query->orderByRaw('id desc , created_at desc');
        $orders = $query->where('eid',$eid)->paginate(request('per_page', 15));
        return Api::success($orders);
    }

     /**
     * 获取用户的阅读记录
     * @Route(path=/api/h5/my-reading-records)
     */
    public function readingRecords()
    {
        $userId = auth('web')->user()->id; // 获取当前认证的用户ID
        $eid = auth('web')->user()->eid;
        
        // 获取用户一次性付费购买的书籍ID
        $paidEbooks = Orders::where('user_id', $userId)
            ->where('status', 2)
            ->where('ebook_id', '<>', '') // 使用 '<>' 代替 '!=' 来提高可读性
            ->pluck('ebook_id');
        
        $query = UserReadingRecords::where('user_id', $userId)->where('eid', $eid);
        
        // 检查请求中是否有 book_id 参数
        $bookId = request('book_id');
        if ($bookId) {
            // 如果有 book_id 参数，只获取该书籍的阅读记录
            $records = $query->where('ebook_id', $bookId)->where(function ($query) use ($paidEbooks, $bookId) {
                $query->whereIn('ebook_id', $paidEbooks)
                      ->orWhereHas('ebook', function ($query) use ($bookId) {
                          $query->where('id', $bookId)
                                ->where('is_published', 1); // 只关联已发布的书籍
                      });
            })->first();
        } else {
            // 对于一次性付费的书籍，即使下架也显示阅读记录
            $query->where(function ($query) use ($paidEbooks) {
                $query->whereIn('ebook_id', $paidEbooks)
                      ->orWhereHas('ebook', function ($query) {
                          $query->where('is_published', 1); // 只关联已发布的书籍
                      });
            });
        
            // 对于免费或会员书籍，如果下架则不显示阅读记录
            $query->whereDoesntHave('ebook', function ($query) {
                $query->where('is_published', 2);
            });
        
            // 预加载已发布的书籍
            $query->with(['ebook' => function ($query) {
                $query->where('is_published', 1);
            }])->orderByRaw('updated_at desc');
        
            // 分页查询
            $records = $query->paginate(request('per_page', 15));
        
            // 确保付费书籍即使下架也能被检索到
            $records->getCollection()->transform(function ($record) use ($paidEbooks) {
                if (!$record->ebook && in_array($record->ebook_id, $paidEbooks)) {
                    $record->ebook = Ebooks::where('id', $record->ebook_id)->first();
                }
                return $record;
            });
        }
        
        return Api::success($records);
    }
    
    
     /**
     * 创建用户的阅读记录
     * @Route(path=/api/h5/create-reading-record method=post)
     */
    public function createReadingRecord()
    {
        $userId = auth('web')->user()->id; // 获取当前认证的用户ID
        $ebookId = request('book_id'); // 关联的电子书id
        $startTime = request('start_time'); // 开始阅读时间
        $endTime = request('end_time'); // 结束阅读时间
        $lastReadTime = request('last_read_time'); // 最后阅读的时间
        $progress = request('progress'); // 阅读进度
        $isCompleted = request('is_completed'); // 电子书是否已读完
        
        // 确保时间是有效的日期时间字符串
        $startTime = new Carbon($startTime);
        $endTime = new Carbon($endTime);
        $lastReadTime = new Carbon($lastReadTime);
        
        // 计算阅读时长
        $readingDuration = $endTime->diffInMinutes($startTime); // 以分钟为单位计算时长
        
        // 如果您需要计算从开始到最后一次阅读的总时长
        $totalReadingDuration = $lastReadTime->diffInMinutes($startTime);
        $sid = auth('web')->user()->sid;
        $eid = auth('web')->user()->eid;
    
        // 直接从请求中获取数据
        $validatedData = [
            'ebook_id' => $ebookId,
            'start_time' => $startTime,
            'end_time' => $endTime,
            'duration' => $readingDuration,
            'last_read_time' => $lastReadTime,
            'progress' => $progress,
            'is_completed' => $isCompleted,
            'sid' => $sid,
            'eid' => $eid
        ];
    
        // 检查必要的字段是否存在
        if (!array_filter($validatedData)) {
            return Api::fail('缺少必要的请求参数', 400);
        }
        
        // 检查是否已存在记录
        $record = UserReadingRecords::where('user_id', $userId)
                                     ->where('ebook_id', $ebookId)
                                     ->first();
        if ($record) {
            // 如果记录存在，更新记录
            $record->update([
                'end_time' => $validatedData['end_time'],
                'duration' => $readingDuration, // 单次阅读时长
                'total_duration' => $record->total_duration + $readingDuration, // 累加阅读时长
                'last_read_time' => $validatedData['last_read_time'],
                'progress' => $validatedData['progress'],
                'is_completed' => $validatedData['is_completed'],
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        } else {
            // 创建阅读记录
            $record = new UserReadingRecords();
            $record->user_id = $userId;
            $record->ebook_id = $validatedData['ebook_id'];
            $record->start_time = $validatedData['start_time'];
            $record->end_time = $validatedData['end_time'];
            // 将计算结果保存到记录中
            $record->duration = $readingDuration;
            //可以将总阅读时长也保存
            $record->total_duration = $totalReadingDuration;
    
            $record->last_read_time = $validatedData['last_read_time'];
            $record->progress = $validatedData['progress'];
            $record->is_completed = $validatedData['is_completed'];
            $record->created_at = date('Y-m-d H:i:s');
            $record->sid = $validatedData['sid'];
            $record->eid = $validatedData['eid'];
            $record->save();
        }
    
        return Api::success([
            'msg' => '阅读记录创建成功！',
            'record' => $record
        ]);
    }
}